package com.knowif.aliOSS.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

import org.omg.CORBA.SystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DownloadFileRequest;
import com.aliyun.oss.model.DownloadFileResult;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.knowif.aliOSS.bean.AliImageStyleBean;
import com.knowif.aliOSS.bean.util.AliImageStyleBeanUtil;
import com.knowif.aliOSS.config.util.AliyunFileConfigUtil;
import com.knowif.aliOSS.config.util.AliyunImageConfigUtil;
import com.knowif.aliOSS.config.util.AliyunOSSConfigUtil;
import com.knowif.aliOSS.enumConfig.AliOSSConfig;
import com.knowif.util.commonUtil.FileUtil;
import com.knowif.util.commonUtil.StringUtil;

@Service
public class AliyunFileUtil {
	
	@Autowired
	private AliyunImageConfigUtil aliyunImageConfigUtil;
	
	@Autowired
	private AliyunFileConfigUtil aliyunFileConfigUtil;
	
	@Autowired
	private AliyunOSSConfigUtil aliyunOSSConfigUtil;
	
	@Autowired
	private AliImageStyleBeanUtil aliImageStyleBeanUtil;
	
	/**
	 * 得到ossClient对象，用于文件、图片等数据进行上传
	 * 
	 * @author xingyao
	 * @date 2017年4月5日
	 * @describe
	 * @return
	 */
	private OSSClient getOUTOSSClient() {
		return new OSSClient(aliyunOSSConfigUtil.getOss_outer_Domain(), aliyunOSSConfigUtil.getAccess_Key_Id(), aliyunOSSConfigUtil.getAccess_Key_Secret());
	}
	
	
	/**
	 * 得到ossClient对象，用于文件、图片等数据进行上传
	 * @author xingyao
	 * @date 2017年4月5日
	 * @describe
	 * @return
	 */
	private OSSClient getInnerOSSClient() {
		return new OSSClient(aliyunOSSConfigUtil.getOss_Inner_Domain(), aliyunOSSConfigUtil.getAccess_Key_Id(), aliyunOSSConfigUtil.getAccess_Key_Secret());
	}

	/**
	 * 将图片上传到阿里云服务器中
	 * @author xingyao
	 * @date 2017年4月5日
	 * @describe
	 * @return
	 */
	public static String imageUpload(String filePath) {
		return filePath;
	}

	/**
	 * 文件上传工具类
	 * 
	 * @author xingyao
	 * @date 2017年4月5日
	 * @describe
	 * @param fileName
	 *            上传后的文件名字
	 * @return
	 */
	public String fileUpload(AliOSSConfig aliOSSConfig) {
		OSSClient ossClient = getOUTOSSClient();
		InputStream inputStream;
		try {
			String filePath = aliOSSConfig.getFilePath();
			inputStream = new FileInputStream(aliOSSConfig.getFileName());
			ossClient.putObject(aliOSSConfig.getBucketName(), filePath, inputStream);
			return filePath;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		ossClient.shutdown();
		return "";
	}
	
	/**
	 * 上传文件
	 * @author xingyao
	 * @date 2017年4月25日
	 * @describe
	 * @param aliOSSConfig
	 * @param inputStream
	 * @return
	 */
	public String fileUpload(AliOSSConfig aliOSSConfig,InputStream inputStream){
		OSSClient ossClient = getOUTOSSClient();
		String filePath = aliOSSConfig.getFileName();
		ossClient.putObject(aliOSSConfig.getBucketName(), filePath, inputStream);
		ossClient.shutdown();
		return filePath;
	}
	
	/**
	 * 
	 * @author xingyao
	 * @date 2017年4月26日
	 * @describe
	 * @param aliOSSConfig
	 * @return String 文件下载路径
	 * @throws SystemException
	 */
	public String downloadFile(AliOSSConfig aliOSSConfig) throws SystemException{
		// 创建OSSClient实例
		OSSClient ossClient = getOUTOSSClient();
		// 下载请求，10个任务并发下载，启动断点续传
		DownloadFileRequest downloadFileRequest = new DownloadFileRequest(aliOSSConfig.getBucketName(), aliOSSConfig.getFileName());
		downloadFileRequest.setDownloadFile(FileUtil.getProjectPath()+"/"+aliOSSConfig.getName());
		downloadFileRequest.setTaskNum(aliyunFileConfigUtil.getTaskNum());
		downloadFileRequest.setEnableCheckpoint(true);
		// 下载文件
		DownloadFileResult downloadRes;
		try {
			downloadRes = ossClient.downloadFile(downloadFileRequest);
			// 下载成功时，会返回文件的元信息
			downloadRes.getObjectMetadata();
			return FileUtil.getProjectPath()+"/"+aliOSSConfig.getName();
		} catch (Throwable e) {
			e.printStackTrace();
			return null;
		}finally{
			ossClient.shutdown();
		}
	}
	
	/**
	 * 文件下载
	 * @author xingyao
	 * @date 2017年4月26日
	 * @describe  
	 * @param aliOSSConfig  
	 * @param folderName	文件夹的名字，将文件同一下载到该文件夹中
	 * @return
	 * @throws SystemException
	 */
	public void downloadFile(AliOSSConfig aliOSSConfig,String folderName) throws SystemException{
		// 创建OSSClient实例
		OSSClient ossClient = getInnerOSSClient();
		// 下载请求，10个任务并发下载，启动断点续传
		FileUtil.fileNotExist2Create(folderName);
		DownloadFileRequest downloadFileRequest = new DownloadFileRequest(aliOSSConfig.getBucketName(), aliOSSConfig.getFileName());
		downloadFileRequest.setDownloadFile(folderName+File.separator+aliOSSConfig.getName());
		downloadFileRequest.setTaskNum(aliyunFileConfigUtil.getTaskNum());
		downloadFileRequest.setEnableCheckpoint(true);
		// 下载文件
		DownloadFileResult downloadRes;
		try {
			downloadRes = ossClient.downloadFile(downloadFileRequest);
			// 下载成功时，会返回文件的元信息
			downloadRes.getObjectMetadata();
		} catch (Throwable e) {
			e.printStackTrace();
		}finally{
			ossClient.shutdown();
		}
	}

//	public void main(String[] args) throws SystemException {
//		downloadFile(AliOSSConfig.ALIFIlE_STUDENT.setFileName("xitu_student_work/1/139/20132101-熊乾超-Java课后习题.zip"),"C:\\Users\\Administrator\\Desktop");
//	}
	
	/**
	 * 得到阿里云服务器OSS里面的图片url
	 * 
	 * @author xingyao
	 * @date 2017年4月5日
	 * @describe
	 * @param aliOSSConfig
	 * @return
	 * @throws SystemException 
	 */
	public String getAliImageUrl(AliOSSConfig aliOSSConfig) throws Exception {
		if(!FileUtil.isImage(aliOSSConfig.getFileName())){
			throw new Exception("不是图片格式的配置文件");
		}
		OSSClient ossClient = getOUTOSSClient();
		// 过期时间10分钟
		Date expiration = null;
		if(aliOSSConfig.getTime() < 0){
			expiration = new Date(new Date().getTime() +  aliyunImageConfigUtil.getImageDefaultTime());
		}else{
			expiration = new Date(new Date().getTime() +  aliOSSConfig.getTime());
		}
		GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(aliOSSConfig.getBucketName(),
				aliOSSConfig.getFileName(), HttpMethod.GET);
		req.setExpiration(expiration);
		URL imageUrl = ossClient.generatePresignedUrl(req);
		return imageUrl.toString();
	}
	
	
	
	/**
	 * 得到保存在阿里云服务器中的作业地址
	 * @author xingyao
	 * @date 2017年4月22日
	 * @describe
	 * @param aliOSSConfig
	 * @return
	 * @throws SystemException
	 */
	public String getAliWorkUrl(AliOSSConfig aliOSSConfig) throws Exception{
		if(!FileUtil.isCompressFile(aliOSSConfig.getFileName())){
			throw new Exception("不是压缩文件的配置");
		}
		OSSClient ossClient =  getOUTOSSClient();
		Date expiration = null;
		if(aliOSSConfig.getTime() < 0){
			expiration = new Date(new Date().getTime() +   aliyunImageConfigUtil.getImageDefaultTime());
		}else{
			expiration = new Date(new Date().getTime() +  aliOSSConfig.getTime());
		}
		GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(aliOSSConfig.getBucketName(),
				aliOSSConfig.getFileName(), HttpMethod.GET);
		req.setExpiration(expiration);
		URL workUrl = ossClient.generatePresignedUrl(req);
		return workUrl.toString();
	}

	/**
	 * 上传文件测试用例
	 */
//	public static void main(String[] args) throws SystemException {
//		AliImageStyleBean ali = new AliImageStyleBean();
//		ali.setWidth(150);
//		ali.setHeight(150);
//		String path1 = getAliImageUrl(
//				AliOSSConfig.ALIIMAGE_STUDENT.setFileName("xitu_student_image/4/16/10/1492309229976iuETB2aK7gNPT8.jpg"),ali);
//		System.out.println(path1);
//	}

	/**
	 * 得到阿里云服务器OSS里面的图片url,并添加得到图片的样式
	 * 
	 * @author xingyao
	 * @date 2017年4月5日
	 * @describe
	 * @param aliOSSConfig
	 * @return
	 */
	public String getAliImageUrl(AliOSSConfig aliOSSConfig, AliImageStyleBean aliImageStyleBean) {
		OSSClient ossClient =  getOUTOSSClient();
		// 过期时间10分钟
		Date expiration = new Date(new Date().getTime() +   aliyunImageConfigUtil.getImageDefaultTime());
		GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(aliOSSConfig.getBucketName(),
				aliOSSConfig.getFileName(), HttpMethod.GET);
		req.setExpiration(expiration);
		if(!StringUtil.isEmpty(aliImageStyleBeanUtil.getImageStyle(aliImageStyleBean))){
			req.setProcess(aliImageStyleBeanUtil.getImageStyle(aliImageStyleBean));
		}
		URL imageUrl = ossClient.generatePresignedUrl(req);
		return imageUrl.toString();
	}
	
	
	public String getWebHeadImage4Aliyun(AliOSSConfig aliOSSConfig){
		/*stusiri_web项目中mian页面的头部图片大小*/
		AliImageStyleBean aliImageStyleBean = new AliImageStyleBean();
		aliImageStyleBean.setHeight(36);
		aliImageStyleBean.setWidth(36);
		return getAliImageUrl(aliOSSConfig, aliImageStyleBean);
	}

}
